package com.apesource.bookBuy.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUtil {
	
	public static boolean sendEmail(String email, String code) {
		boolean isok = false;
		// 配置
		Properties prop=new Properties();
		// 设置邮件服务器主机名，这里是163
		prop.put("mail.host","smtp.163.com" );
		// 发送邮件协议名称
		prop.put("mail.transport.protocol", "smtp");
		// 是否认证
		prop.put("mail.smtp.auth", true);

		try {
			// 创建会话对象
			Session session = Session.getDefaultInstance(prop, new Authenticator() {
		      public PasswordAuthentication getPasswordAuthentication() {
		    	// 认证信息，需要提供"用户账号","授权码"
		    	return new PasswordAuthentication("19119640993@163.com", "BHS3SBf3hcfrARwf");
		      }
		    });
		    // 是否打印出debug信息
		    session.setDebug(true);
		 
		    // 创建邮件
		    Message message = new MimeMessage(session);
		    // 邮件发送者
		    message.setFrom(new InternetAddress("19119640993@163.com"));
		    // 邮件接受者
		    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
		    // 邮件主题
		    message.setSubject("验证码");
		    String content = "<html><head></head><body><h1>你的验证码是"+code+"</h1></body></html>";
		    message.setContent(content, "text/html;charset=UTF-8");
		    // Transport.send(message);
		    // 邮件发送
		    Transport transport = session.getTransport();
		    transport.connect();
		    transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
		    isok = true;
		  } catch (Exception e) {
		    e.printStackTrace();
		  }
		return isok;
	}

}
